import type { ResponsePaginationData } from '@/utils/request';
import { SUCCESS_CODE } from '@/utils/request';
import type { RequestData } from '@ant-design/pro-table';
import type { ReserveDetail, ReserveTableListItem } from './data';
import { message } from 'antd';
import { request } from 'umi';

type Pagination = { page?: number; pageSize?: number };

/**
 * 获取全部预约记录
 *
 * @param params
 */
export async function findReservationList(
  params: Pagination & { status?: number; startSearchTime?: string; endSearchTime?: string },
): Promise<RequestData<ReserveTableListItem>> {
  const { page = 1, pageSize = 20, status, startSearchTime, endSearchTime } = params;
  const res: ResponsePaginationData<ReserveTableListItem> = await request('/reservation', {
    params: {
      page,
      pageSize,
      startDate: startSearchTime,
      endDate: endSearchTime,
      status,
    },
  });
  if (res?.code !== SUCCESS_CODE) {
    return { success: false, total: 0, data: [] };
  }

  return {
    success: true,
    total: res.data.total,
    data: res.data.list,
  };
}

/**
 * 获取全部预约记录
 *
 * @param params
 */
export async function getReservationList(
  params: Pagination & {
    status?: number;
    startSearchTime?: string;
    endSearchTime?: string;
    plateNumber?: string;
    order_status?: number;
    mobile?: string;
  },
): Promise<RequestData<ReserveTableListItem>> {
  const { page = 1, pageSize = 10, startSearchTime, endSearchTime } = params;
  const res: ResponsePaginationData<ReserveTableListItem> = await request(
    '/reservation/get_reserve_orders',
    {
      data: {
        ...params,
        page,
        pageSize,
        startTime: startSearchTime,
        endTime: endSearchTime,
        status: params.order_status,
      },
      method: 'POST',
    },
  );
  if (res?.code !== SUCCESS_CODE) {
    return { success: false, total: 0, data: [] };
  }

  return {
    success: true,
    total: res.data.total,
    data: res.data.list,
  };
}

/**
 * 获取预约记录详细信息
 */
export async function findReserveDetail(params: {
  id: string;
}): Promise<{ success: boolean; data?: ReserveDetail }> {
  const res = await request(`/reservation/${params.id}`);

  if (!res || res.code !== SUCCESS_CODE || !res.data) {
    message.error('获取失败');
    return { success: false };
  }

  const { data } = res;

  return {
    success: true,
    data: {
      ...data,
      createTime: data.createTime || '未知',
      expireDate: data.expireDate || '未知',
      reservationEndDate: data.reservationEndDate || '未知',
      reservationStartDate: data.reservationStartDate || '未知',
      updateTime: data.updateTime || '未知',
    },
  };
}
